using Basis;
using Miya.ActionManager;
using NL;
using NL.AdreesableAsset;
using NL.Advanced;
using NL.ControllerInteface;
using System;
using System.Collections;
using UnityEngine;

namespace Miya.EmisssionLauncher
{

    public enum LaunchMovingModel
    {
        none = 0,
        StopMoving = 1,
        StopMovingWhole = 2,
    }

    public enum LaunchActionModel
    {
        RuntimeWithAction = 0,
        JustActorWothAction = 1,
    }



    public class LauncherWithAM : Launcher/*,ILauncher*/
    {




        public bool ShowUI { get; set; }


        [Header("需要呼叫得动作行为,和等待得行为窗口.")]
        public string ActionName = "attack";
        public string ActionEvent = "FIRE";

        [Header("技能前摇.技能释放中是否面向目标")]
        public bool FacingWithActionPre = true;
        public bool FacingWithActioning = true;



        [Header("发射得时候允许移动.")]
        public LaunchMovingModel LaunchMoving = LaunchMovingModel.none;




        [Header("后摇等待时间")]
        public float LaunchEndWaiting;

        [Header("使用直接结算,直接结算得延迟.<0 无效 ")]
        public float HitDirectDelay = -1f;




        public float Mana = 0f;
        public float Range = 5f;

        public bool UseOwnerProperty = false;
        public NLIni _BBIni;




        protected IEmissionOwner _EmissionOwner;
        protected IMaster _Master;
        protected IAMOwner _AMOwner;
        protected override void Awake()
        {
            base.Awake();

            _AMOwner = GetComponentInParent<IAMOwner>();
            _EmissionOwner = GetComponentInParent<IEmissionOwner>();
            _Master = GetComponentInParent<IMaster>();
            Emissions = GetComponentsInChildren<Emission>();

        }

        protected override void _LoadInfo()
        {
            base._LoadInfo();

            if (Info == null) return;

            //下面是 根据数据源.重置相关 参数.
            Mana = Info["energy"].AsFloatDefault(Mana);
            Range = Info["range"].AsFloatDefault(Range);






            //读取子弹
            var str = Info["bb"].AsString;
            if (!string.IsNullOrEmpty(str))
            {
                Mod_Bullet = AA.LoadAndWait(str);
            }

            //读取动作
            str = Info["action"].AsString;
            if (string.IsNullOrEmpty(str))
            {
                var arr = str.Split(';');
                if (arr.Length > 0)
                    ActionName = arr[0];
                if (arr.Length >= 1)
                    ActionEvent = arr[1];
            }

        }










        protected virtual bool _CanLaunch(bool stop = false)
        {
            if (CombatOwner == null)
                CombatOwner = GetComponentInParent<ICombatOwner>();


            //if (_Owner.UnitStateInclude(UnitStateMask.skillno))
            //    return false;

            //TODO:wcp，临时处理，自己是monster,攻击距离<=3，不是阻挡者并且没有被阻挡，不能攻击
            //var monster = _Owner.gameObject.GetComponent<Monster>();
            //if (monster != null)
            //{
            //    var combateRange = ((ICombatOwner) monster).GenarateRange();
            //    var luobo = (ILuobo) monster;
            //    if (combateRange <= 3 && luobo.MaxCount <= 0 && !monster.UnitStateInclude(UnitStateMask.block) && monster.NowBlocker == null)
            //    {
            //        return false;
            //    }
            //}

            //if (Mod_Bullet != null)
            //{
            //    var _slaver = Mod_Bullet.GetComponent<ISlaver>();
            //    if (_slaver != null)
            //    {
            //        if (_MasterOwner == null)
            //            _MasterOwner = ComabteOwner.gameObject.GetComponent<IMaster>();

            //        if (_MasterOwner != null && !_MasterOwner.CanSumon(this))
            //        {
            //            return false;
            //        }
            //    }
            //}
            /*
                        if (SkillType == SkillType.Summon)
                        {
                            if (_MasterOwner == null)
                                _MasterOwner = _Owner.gameObject.GetComponent<IMaster>();

                            if (_MasterOwner != null && !_MasterOwner.CanSumon(this))
                            {
                                return false;
                            }
                        }*/


            //if (_SkillOwer != null)
            //    return _SkillOwer.CanCast(this,stop);
            //else
            return true;
        }



        protected virtual void OnAMAction(string action)
        {

        }



        public bool _Casting = false;





        protected void _LaunchAction()
        {
            if (CombatOwner != null && !string.IsNullOrEmpty(ActionName))
            {
                // 调用动作...
                // return  ComabtOwner.DoCombatAction(ActionName);

            }

            //   return null;
        }

        public bool IsPlaying => State >= CastingState.Prepare && State < CastingState.Ending;

        bool _CanLaunchContinue
        {
            get
            {
                if (CombatOwner != null && !CombatOwner.Living) return false;

                return true;
            }
        }
        long __US_UDID = 0;

        //IEnumerator _LaunchRuner()
        //{

        //    // Prepare
        //    State = CastingState.Prepare;



        //    //先获取 技能释放得目标点


        //    var _prepare = _DoPrepare();

        //    while (_prepare.MoveNext())
        //    {

        //        yield return 1;
        //    }


        //    _LastLaunchTime = Time.time;

        //    // PreAction
        //    State = CastingState.PreAction;
        //    //LOG.Add($"[Launcher._LaunchRuner]:CastingState.PreAction :{name}");

        //    float _timeinir = Time.time;



        //    // 需要检查 是否可以 继续施展技能的(比如 目标死亡) ---FHF
        //    if (!_CanLaunchContinue)
        //    {

        //        Stop("!CanCasting");

        //        yield break;

        //    }
        //    else
        //    {

        //    }



        //    // 协调动作.
        //    var waitAni = false;
        //    float waittime = Time.time;
        //    if (CombatOwner != null && !string.IsNullOrEmpty(ActionName))
        //    {


        //        // 调用动作...
        //        var amaction = _AMOwner?.Play(ActionName);
        //        if (amaction != null)
        //        {
        //            OnAMAction(ActionName);

        //            //协同 动作 生命周期
        //            amaction.Wait((w) =>
        //                {
        //                },
        //                (ww) =>
        //                {
        //                    //避免 动作结束后 过早的调用 Stop.同时 Launch还没执行完.
        //                    //State = CastingState.None;
        //                    //Stop("ActionEnd");
        //                });

        //            if (!string.IsNullOrEmpty(ActionEvent))
        //            {
        //                waitAni = true;

        //                amaction.WaitTimer(ActionEvent, (w, s) =>
        //                {
        //                    LOG.Add($"[Launch._LaunchRuner];WaitTime({s}).............");
        //                    waitAni = false;
        //                });
        //                amaction.Wait(null, (w) =>
        //                {
        //                    waitAni = false;
        //                });
        //            }

        //        }
        //    }

        //    // 需要在动作实战过程中  实时检查 是否可以 继续施展技能的(比如 目标死亡)  ---FHF

        //    while (waitAni)
        //    {
        //        if (!_CanLaunchContinue)
        //        {

        //            Stop("CanCasting"); yield break;
        //        }

        //        if (Time.time - waittime > Mathf.Max(2, Life))
        //        {
        //            Stop("Timeout for action ");

        //            yield break;
        //        }



        //        if (!string.IsNullOrEmpty(ActionName))
        //        {
        //            var nowAction = _AMOwner?.GetNowActionName();
        //            if (!string.IsNullOrEmpty(nowAction) && nowAction != ActionName)
        //            {
        //                Stop("nowAction!= ActionName");

        //                yield break;
        //            }
        //        }

        //        yield return 1;
        //    }



        //    //ComabteOwner.transform.forward = LaunchForward;

        //    //开始 引导
        //    State = CastingState.Action;


        //    _DoLaunchBegin();


        //    //StartCoroutine(_DoShoot());
        //    var _shooter = _DoShoot();
        //    if (_shooter != null)
        //    {

        //        while (_shooter.MoveNext())
        //        {

        //            yield return new WaitForSeconds(Duration);
        //        }
        //    }


        //    if (LaunchEndWaiting > 0)
        //    {
        //        yield return new WaitForSeconds(LaunchEndWaiting);
        //    }


        //    if (Life > 0)
        //    {
        //        while (Life > 0 && Time.time - _timeinir < Life)
        //            yield return 0;
        //    }






        //    //结束引导
        //    _DoLaunchEnd();




        //    State = CastingState.Ending;

        //    //主动监听 动作协同
        //    if (!string.IsNullOrEmpty(ActionName))
        //    {
        //        while (_AMOwner != null && _AMOwner.GetNowActionName() == ActionName)
        //        {
        //            yield return 0;
        //        }
        //    }



        //    State = CastingState.None;
        //    //LOG.Add($"[Launcher._LaunchRuner]:CastingState.None :{name}");


        //}




        protected virtual IEnumerator _DoShoot()
        {
            LOG.Add($"[Launcher._DoShoot]::{name}");
            //循环每轮发射的波次

            var num = COUNT;// FixCount();

            for (int i = 0; i < num; i++)
            {
                // if (FacingWithActioning)
                //     _Owner.gameObject.ADDTurner().TurnTo(LaunchForward);

                StartCoroutine(_DoLuanchLoopOne());

                yield return Duration;
            }
        }









        public bool EFF_Fire_SetAsChild = false;
        // 发射一颗子弹

        void _AddBBAttacker(GameObject bb)
        {

        }

        protected void CreateHalo(int _id, ICombatOwner _owner, Action<GameObject> _on)
        {
            if (_on == null)
                return;
            //var haloInfo = HaloDic.GETByID(_id);
            //检查是否打到在场的数量上限
            //var maxCount = haloInfo["max_count"].AsIntDefault(int.MaxValue);
            // var record = GetComponentInParent<TeamManager>().Halos;
            //var curCount = record.Count(_Owner.Camp,_id);
            //if (curCount >= maxCount)
            //    return;
            //string mod = haloInfo["mod"];
            //if (string.IsNullOrEmpty(mod))
            //{
            //    //使用内置prefab
            //    mod = "halo";
            //}

            //record.AddHalo(_Owner.Camp, _id);

            //AA.LOAD<GameObject>(mod, delegate(string _s, GameObject _o)
            //{
            //    if (_o == null)
            //        return;
            //    if (_owner == null)
            //        return;
            //    //附加Attacker
            //    var halo = BPoolMan.POOL["halo"].Create(_o);
            //    var haloScript = halo.GetComponent<Halo>();
            //    haloScript.id = _id;
            //    haloScript.SetCombatOwner(_owner, 1);
            //    haloScript.Duration = haloInfo["duration"];
            //    haloScript.BeatImediatly = haloInfo["beatImediatly"].AsIntDefault(1) == 1;
            //    haloScript.RemoveBuff = haloInfo["remove_buff"].AsIntDefault(1) == 1;
            //    string lifeMode = haloInfo["lifeMode"];
            //    if (!string.IsNullOrEmpty(lifeMode))
            //    {
            //        var lifeIni = new NLIni(lifeMode,';');
            //        if (lifeIni["type"] == "time")
            //        {
            //            haloScript.DeadMode = BulletDeadMode.ByLife;
            //            haloScript.DeadData = lifeIni["data"];
            //        }
            //        else if (lifeIni["type"] == "count")
            //        {
            //            haloScript.DeadMode = BulletDeadMode.HitCount;
            //            haloScript.DeadData = lifeIni["data"];
            //        }
            //    }
            //    else
            //    {
            //        haloScript.DeadMode = BulletDeadMode.None;
            //    }
            //    halo.GetComponent<IRange>().Reset(haloInfo["range"]);
            //    foreach (var att in haloInfo.Attackers)
            //    {
            //        halo.gameObject.AddComponent<Attacker>().Set(att,_Fixes).SetDisposable(true);
            //    }

            //    _on.Invoke(halo);
            //});
        }

        void _ProcHaloBB(NLIni _info, Vector3 _from, Vector3 _dir, Transform _target)
        {
            int haloId = _info["id"];
            CreateHalo(haloId, CombatOwner, (g) =>
            {
                //if(APP.GameMode == E_GameMode.Normal)
                //    _from = _from.GetGPSPosition();
                g.transform.position = _from;
                g.transform.forward = _dir;
                OnLaunchOne(g, _target == null ? null : _target.gameObject);
            });
        }

        void _ProcSummonBB(NLIni info, Vector3 _from, Vector3 _dir, Transform _target)
        {
            //string monsterId = info["id"];
            //var monsterInfo = Army.GetMonsterInfo(monsterId);
            //if (monsterInfo == null) 
            //    return;
            //string mod = monsterInfo["mod"];
            //if(string.IsNullOrEmpty(mod))
            //    return;
            //AA.LOAD<GameObject>(mod, (w, o) =>
            //{
            //    if (o == null) return;
            //    if(gameObject == null)
            //        return;
            //    var bb = BPoolMan.POOL["BB"].Create(o);
            //    _from = _from.GetGPSPosition();
            //    bb.transform.position = _from;
            //    bb.transform.forward = _dir;
            //    //设置召唤物属性
            //    var modifyInfo = new NLInfo(monsterInfo);
            //    string prop = modifyInfo["property"];
            //    Annexs ownerProp = new Annexs(_Owner.GetProperty().ToString());
            //    modifyInfo["property"] = ownerProp.ToString();
            //    modifyInfo["state"] = info["state"];
            //    modifyInfo["homehurt"] = APP.SEISE_MONSTER_HOME_DAMAGE;
            //    modifyInfo["addprop"] = prop;
            //    bb.INFOSet(modifyInfo);

            //    if (info.Has("life"))
            //    {
            //        int life = info["life"];
            //        bb.GetComponent<IDeadable>().DelayDead(life);
            //    }

            //    var stateInfo = UnitStateDict.Get(info["state"]);
            //    if (!stateInfo.UnitState.Contains(UnitStateMask.moveno))
            //    {
            //        //召唤物可行走
            //        var transer = bb.GetComponent<Transer>();
            //        if (transer != null)
            //        {
            //            var (targetPos,points) = Map.Instance.GetNearestSegmentAndRemainPath(bb.transform.position);
            //            transer.Move(targetPos).WaitRouteArrived(() =>
            //            {
            //                transer?.Route(points).PointOnRoutePath();
            //            });
            //        }
            //    }

            //    //设置属性继承
            //    OnLaunchOne(bb, _target == null ? null : _target.gameObject);
            //});
        }

        IMaster _MasterOwner;
        protected virtual void OnLaunchOne(GameObject _bb, GameObject _target)
        {
            _bb.GetComponent<BB>()?
                .SetCombatOwner(CombatOwner, 1)
                .SetTarget(_target)
                .SetLauncherOwner(gameObject);
            
            //_bb.GetComponent<BB>()?.SetLevelStateOwner(_LevelOwner);
            //_bb.GetComponent<BB>()?.SetShowUI(ShowUI);

            //var co = _bb.GetComponent<ICombatOwner>();
            //if(co != null && ComabteOwner!=null)
            //    co.Camp = ComabteOwner.Camp;

            //var _slaver = _bb.GetComponent<ISlaver>();
            //if (_slaver != null)
            //{
            //    if(_MasterOwner == null)
            //        _MasterOwner= ComabteOwner.gameObject.GetComponent<IMaster>();

            //    if (_MasterOwner != null)
            //    {
            //        if (!_MasterOwner.CanSumon(this))
            //        {
            //            _bb.gameObject.SetActive(false);
            //            return;
            //        }

            //        _MasterOwner.AddSlaver(this, _slaver);
            //        _slaver.SetMaster(_MasterOwner);
            //    }
            //}

            //var noop = _bb.GetComponent<Noop>();
            //if (noop)
            //{
            //    noop.SetLevelStateOwner(_LevelOwner);
            //}

            _ONLaunchOne?.Invoke(_bb);
        }

        protected virtual IEnumerator _DoPrepare()
        {

            //处理方向

            if (FacingWithActionPre)
            {
                var target = LaunchForward;
                ////处理方向
                var turner = CombatOwner.gameObject.ADDTurner().TurnTo(target);
                while (turner.Turning)
                {
                    yield return 1;
                }
                CombatOwner.transform.forward = target;
            }

            yield return 1;
        }






        Action<GameObject> _ONLaunchOne;
        public LauncherWithAM WaitOne(Action<GameObject> _on)
        {
            _ONLaunchOne = _on; return this;
        }

        AMAction _NowAMAction;
        protected override void _DoStop(string code = "")
        {
            base._DoStop(code);



            if (_NowAMAction != null && State >= CastingState.Prepare)
            {
                _NowAMAction.End();
            }

            LOG.Add($"[Launch.Stop({code})]............");
        }

        protected virtual void Clear()
        {
            /*if (SkillType == SkillType.Summon)
            {
                var hasKey = _BBIni.Has("dead");
                if (hasKey && _BBIni["dead"] == "0")
                {
                }
                else
                {
                    //remove summon children
                    var master = _Owner.gameObject.GetComponent<IMaster>();
                    if (master != null)
                    {
                        var slavers = master.Slavers(this);
                        if (slavers != null)
                        {
                            foreach (var slaver in slavers)
                            {
                                var unit = slaver.gameObject.GetComponent<Unit>();
                                if (unit != null)
                                {
                                    unit.Dead();
                                }
                            }
                        }
                    }
                }
            }*/
        }

    }

}

